<template>
<!--  <div class="enter_wrap">-->
<!--    思考：<p v-html="result"/>-->
<!--    回答：<p v-html="content"/>-->
<!--  </div>-->
  <div class="ai_wrap">
    <div class="title_area">
      <h3>崇小宝Ai政小助手欢迎您！</h3>
      <p>Deepseek赋能智能化政务服务</p>
    </div>
    <div class="chat_area">
      <div id="chatContent" class="chat_con" ref="scrollWrap">
        <ul class="content chat_list">
          <li v-for="(item,index) in chatList" :key="'aichat'+index" class="chat_item">
            <div class="ai_info" v-if="item.direction===0">
              <img class="ai_portrait" :src="portrait" />
              <span class="ai_name">{{aiName}}</span>
            </div>
            <div :class="item.direction===0?'ai_msg msg_l':'ai_msg msg_r'" >
              <div class="ai_seek" v-if="item.seek">
                <span class="seek_tit">思考：</span>
                <span v-html="item.seek"></span>
              </div>
              <div class="ai_content">
                <span  class="seek_tit" v-if="item.seek&&item.content">回答：</span>
                <span v-html="item.content"></span>
              </div>
<!--              <div class="hot_business" v-if="index===0">-->
<!--                <h6>{{aiTitle}}</h6>-->
<!--                <ul class="hot_wrap">-->
<!--                  <li class="hot_item" v-for="(it,ind) in aiBusiness" :key="'hotBusiness'+ind" @click="intoAiDo(ind)">{{it}}</li>-->
<!--                </ul>-->
<!--              </div>-->
              <div class="hot_business" v-if="index===0">
                <h6>{{hotTitle}}</h6>
                <ul class="hot_wrap">
                  <li class="hot_item" v-for="(it,ind) in hotBusiness" :key="'hotBusiness'+ind" @click="sendMsg(it)">{{it}}</li>
                </ul>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div  id="inputContent" class="input_area">
      <div class="chat_input" v-if="canInput">
        <input id="inputBox" class="real_input" autofocus :placeholder="canInput?'请输入':''" :disabled="!canInput" v-model="inputText" />
        <div class="send_btn" @click="sendMsg()">
          <svg class="icon" style="width: 2.4em;height: 2.4em;fill: #fff;" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8236"><path d="M512 138.28C282.8 138.28 97 295 97 488.21c0 77.3 29.73 148.75 80.06 206.66 25.83 29.71-72.42 147.65-45 179.47 7 8.09 18.54 11.38 33.11 11.38 62.74 0 181.12-60.92 228.14-60.92a37 37 0 0 1 8.35 0.84A488.37 488.37 0 0 0 512 838.14c229.2 0 415-156.67 415-349.93S741.2 138.28 512 138.28z m253.18 545.57c-32.27 27.21-70.08 48.65-112.38 63.74a417.94 417.94 0 0 1-140.8 23.9 427.28 427.28 0 0 1-96.43-10.91 98.84 98.84 0 0 0-22.27-2.43c-32.36 0-72.69 14.23-119.39 30.7-18.46 6.51-40.4 14.25-60.53 20.27 9.2-19.11 18.53-38.77 24.62-57.72 16.63-51.74 1.84-83.62-13.49-101.26C183 602.34 161 546.35 161 488.21c0-73 34.74-142.44 97.82-195.63 32.27-27.21 70.08-48.66 112.38-63.74a426.52 426.52 0 0 1 281.6 0c42.3 15.08 80.11 36.53 112.38 63.74C828.26 345.77 863 415.25 863 488.21s-34.74 142.45-97.82 195.64z" p-id="8237"></path></svg>
        </div>
      </div>
      <div class="seek_loading" v-if="!canInput">
        <svg class="seeking" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="11913"><path d="M913.066667 465.92c-13.653333 0-25.6-11.946667-25.6-25.6v-117.76c0-15.36-8.533333-30.72-22.186667-37.546667L537.6 93.866667c-13.653333-8.533333-30.72-8.533333-44.373333 0L163.84 283.306667c-13.653333 8.533333-22.186667 22.186667-22.186667 37.546666v64.853334c0 13.653333-11.946667 25.6-25.6 25.6s-25.6-11.946667-25.6-25.6v-64.853334c0-34.133333 18.773333-64.853333 47.786667-81.92L467.626667 49.493333c29.013333-17.066667 66.56-17.066667 95.573333 0L892.586667 238.933333c29.013333 17.066667 47.786667 47.786667 47.786666 81.92v117.76c-1.706667 15.36-11.946667 27.306667-27.306666 27.306667zM515.413333 988.16c-17.066667 0-32.426667-3.413333-47.786666-11.946667L138.24 785.066667c-29.013333-17.066667-47.786667-47.786667-47.786667-81.92v-109.226667c0-13.653333 11.946667-25.6 25.6-25.6s25.6 11.946667 25.6 25.6v109.226667c0 15.36 8.533333 30.72 22.186667 37.546666l329.386667 189.44c13.653333 8.533333 30.72 8.533333 44.373333 0l329.386667-189.44c13.653333-8.533333 22.186667-22.186667 22.186666-37.546666V631.466667c0-13.653333 11.946667-25.6 25.6-25.6s23.893333 10.24 23.893334 25.6v71.68c0 34.133333-18.773333 64.853333-47.786667 81.92L563.2 974.506667c-15.36 8.533333-32.426667 13.653333-47.786667 13.653333z" fill="#ffffff" p-id="11914"></path><path d="M597.333333 645.12h-73.386666l-23.893334-71.68h-114.346666l-23.893334 71.68h-73.386666l114.346666-314.026667h78.506667L597.333333 645.12z m-110.933333-124.586667l-35.84-109.226666c-1.706667-6.826667-3.413333-15.36-5.12-27.306667H443.733333c0 8.533333-3.413333 18.773333-5.12 27.306667l-35.84 109.226666h83.626667zM704.853333 329.386667v314.026666h-66.56V329.386667h66.56z" fill="#ffffff" p-id="11915"></path><path d="M112.64 544.426667m-69.973333 0a69.973333 69.973333 0 1 0 139.946666 0 69.973333 69.973333 0 1 0-139.946666 0Z" fill="#ffffff" p-id="11916"></path><path d="M911.36 467.626667m-69.973333 0a69.973333 69.973333 0 1 0 139.946666 0 69.973333 69.973333 0 1 0-139.946666 0Z" fill="#ffffff" p-id="11917"></path><path d="M814.08 646.826667V377.173333c0-23.893333-13.653333-46.08-34.133333-59.733333L546.133333 182.613333c-20.48-11.946667-47.786667-11.946667-68.266666 0l-233.813334 134.826667c-20.48 11.946667-34.133333 34.133333-34.133333 59.733333V648.533333c0 23.893333 13.653333 46.08 34.133333 59.733334L477.866667 841.386667c20.48 11.946667 47.786667 11.946667 68.266666 0l233.813334-134.826667c22.186667-11.946667 34.133333-34.133333 34.133333-59.733333z" fill="#ffffff" opacity=".1" p-id="11918"></path></svg>
      </div>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'
export default {
  name: 'HomeView',
  data() {
    return {
      result: '',
      content: '',
      aiName:"崇小宝",
      inputText:"",
      canInput:true,
      scrollObj:null,
      aiTitle:"您可以在线办理：",
      aiBusiness:["城乡居民基本养老保险参保登记","《食品经营许可证》核发网上预审"],
      portrait:require("../assets/portrait_cz.png"),
      hotTitle:"您可以尝试这样问我：",
      hotBusiness:["城乡居民基本养老保险参保登记","养老保险定期待遇领取资格认证","存量房买卖合同网签备案","《食品经营许可证》核发","新生儿入户","单位参保登记","职工参保登记(灵活就业人员参保登记)"],
      chatList:[
        {direction:0,seek:"",content:"您好，我是“崇小宝”Ai政务小助手，若您有行政审批相关的问题请尽管问我，我随时为您提供专业解答！"}
      ]
    }
  },
  created() {
    //this.fetchData('你好啊')
    this.$nextTick(() => {
      this.scrollObj = new BScroll(this.$refs.scrollWrap, {
        click: true,
      })
    })
  },
  setup() {

  },
  methods: {
    sendMsg(msg){
      if(!this.canInput)return
      var sendMsg = msg || this.inputText
      if(sendMsg===""){
        this.$toast('不能给我发空消息哦！');
        return;
      }
      this.chatList.push({
        direction:1,
        seek:"",
        content: msg || this.inputText
      })
      this.scrollObj.refresh()
      this.scrollObj.scrollTo(0, this.scrollObj.maxScrollY);
      this.fetchData(msg || this.inputText)
      this.inputText = ""
      this.canInput = false
    },
    intoAiDo(index){
      this.$router.push({
        path: '/aiBusiness'+index
      })
    },
      async fetchData(obj) {
          // 若没有配置环境变量，可用百炼API Key将下行替换为：apiKey='sk-xxx'。但不建议在生产环境中直接将API Key硬编码到代码中，以减少API Key泄露风险。
          const apiKey = 'sk-52886024a70d41349a9cc76c654a8bb8';
          const appId = 'fd90f82c8d4b40d8a350390648a03052';// 替换为实际的应用 ID
          const data = {
              input: {
                  prompt: obj
              },
              parameters: {
                  'has_thoughts' : 'true', //是否大脑思考
                  'incremental_output' : 'true' // 增量输出
              },
              debug: {}
          };
          const url = `https://dashscope.aliyuncs.com/api/v1/apps/${appId}/completion`;
          try {
              fetch(url, {
                  responseType: 'stream',
                  method: 'POST', // 或 'PUT' 等，取决于你的需求
                  headers: {
                      'Authorization': `Bearer ${apiKey}`,
                      'Content-Type': 'application/json',
                      'X-DashScope-SSE': 'enable' // 流式输出
                  },
                  body: JSON.stringify(data) // 将JavaScript对象转换为JSON字符串
              }).then(async response =>  {
                  this.chatList.push({
                    direction:0,
                    seek:"",
                    content: ""
                  })
                  const msgIndex = this.chatList.length-1
                  const reader = response.body.getReader();
                  const decoder = new TextDecoder('utf-8');
                  while (true) {
                      const { done, value } = await reader.read();
                      if (done) {
                        this.canInput = true
                        break
                      };
                      const chunk = decoder.decode(value, { stream: true });
                      // 定义正则表达式来匹配 chunk_message 的值，我们只要chunk_message对应的值
                      //因为json数据和text/event-stream数据不同，json数据可以通过.访问chunk_message 的值，
                      //但是text/event-stream数据是个纯文本，不能通过.访问chunk_message，我们用正则表达式来获取需要的数据
                      let pattern_response = /"response"\s*:\s*"([^"]*)"/;
                      let pattern_text = /"text"\s*:\s*"([^"]*)"/;
                      // 使用正则表达式进行匹配
                      let match_response = chunk.toString().match(pattern_response);
                      let match_text = chunk.toString().match(pattern_text);
                      if (match_response) {
                          // 提取匹配到的值
                          let chunkMsg = match_response[1];
                          //deepseek深度思考的内容
                          //this.result +=chunkMsg
                        this.chatList[msgIndex].seek += chunkMsg.replace(/\\n/g, '<br>')
                        this.scrollObj.refresh()
                        this.scrollObj.scrollTo(0, this.scrollObj.maxScrollY);
                        //console.log(chunkMsg)
                      }
                      if (match_text) {
                          //deepseek深度思考后回答的内容
                          let chunkMsg = match_text[1];
                          // 将消息传递给回调函数处理
                          //this.content += chunkMsg
                        this.chatList[msgIndex].content += chunkMsg.replace(/\\n/g, '<br>')
                        this.scrollObj.refresh()
                        this.scrollObj.scrollTo(0, this.scrollObj.maxScrollY);
                        //console.log(chunkMsg)
                      }
                  }
              })
          } catch (error) {
              console.error('请求失败:', error);
          }
      }
  }
}
</script>

<style scoped>
.ai_wrap {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: url("../assets/cz_bj.jpg") #FFFFFF top center no-repeat;
  background-size: contain;
  text-align: left;
  position:relative;
}


.title_area {
  width: 90%;
  height: 12vh;
  overflow: hidden;
  margin: 20px 20px -25px 25px;
  color: #c5ebfd;
  position: absolute;
  top:0;
}

.title_area h3 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom:-5px;
  color: #fff;
}

.title_area p {
  font-size: 14px;
  margin-top: 6px;
}
.chat_area{
  width:100%;
  height:80vh;
  margin-top: 90px;
}
.input_area{
  width:100%;
  height:60px;
  position: absolute;
  bottom:8px;
  background:#fff;
}
.chat_con{
  width:100%;
  height:97%;
  margin: 0 auto;
  overflow: hidden;
  background:#f8f8f8;
}
.chat_list{
  padding:0.6rem;
}
.chat_item{
  overflow: hidden;
}
.chat_input{
  width:90%;
  height:80%;
  position: relative;
  overflow: hidden;
  border:solid 1px #71a4f8;
  margin: 0 auto;
  background: #e8e8e8;
  border-radius: 0.6rem;
}
.real_input{
  width:75%;
  height:90%;
  margin: 2px 5px;
  box-sizing: border-box;
  border: none;
  font-size: 16px;
  background: none;
  position: absolute;
  left:0;
  top:0;
  overflow: hidden;
}
.send_btn{
  width:25%;
  height:101%;
  background: #71a4f8;
  position: absolute;
  right:0;
  top:0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.ai_info{
  width:100%;
  display: flex;
  float:left;
  margin-top: 0.5rem;
  align-items: center;
}
.ai_portrait{
  width:35px;
  height:35px;
  margin-right: 0.5rem;
}
.ai_name{
  color: #1472e6
}
.seek_tit{
  color: #1472e6;
  font-weight: bold;
}
.ai_msg{
  max-width: 85%;
  position: relative;
  margin-top:0.5rem;
  padding:0.5rem;
}
.ai_msg span{
  word-wrap: break-word;
}
.msg_l{
  float:left;
  background: #eae9e9;
  color:#363636;
  margin_bottom:0.8rem;
  border-radius: 0 1rem 1rem 1rem;
}
.msg_r{
  float:right;
  background:#1472e6;
  color:#ffffff;
  margin_bottom:1rem;
  border-radius: 1rem 1rem 0 1rem;
}
.ai_seek{
  color: #9f9c9c;
  padding-bottom: 0.3rem;
}
.ai_content{
  padding-top: 0.3rem;
}
.seek_loading{
  width:90%;
  height:80%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  border:solid 1px #71a4f8;
  margin: 0 auto;
  background: #71a4f8;
  border-radius: 1em;
}
.seeking{
  fill:#fff;
  width:1.9rem;
  height:1.9rem;
  opacity: 0.7;
  animation: rotate 1s ease-in-out infinite;
}
.hot_business{
  width:100%;
  margin-top: 0.5rem;
}
.hot_business h6{
  font-size: 12px;
  color:#9f9c9c;
}
.hot_item{
  display: inline-block;
  padding:0.3rem 0.5rem;
  background:#f2f2f2;
  margin:0.3rem 0.2rem;
  font-size: 12px;
  color:#1472e6;
  border-radius: 0.3rem;
}
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
